<?php

namespace App\Http\Controllers\Admin\Statistics;

use App\Http\Controllers\Admin\BaseController;
use App\Repositories\UserRepositoryEloquent;

use App\User;
use App\Models\Option;
use App\Models\Order;
use App\Repositories\MemberRepositoryEloquent;
use App\Models\Recharge;
use App\Models\Withdrawals;
use App\Models\Commission;
use App\Models\BrokerGroup;
use App\Models\BrokerGroupUser;
use Breadcrumbs, Toastr,Config,Validator;
use Illuminate\Http\Request;
use App\Models\FinancialDetails;

class BrokerGroupController extends BaseController{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        parent::__construct();
        $this->user = $user;


    }

    public function index(Request $request){
        $groups = BrokerGroup::get();
        return view('admin.statistics.group.index',compact('groups'));
    }

    public function create(){
        return view('admin.statistics.group.create');
    }

    public function store(Request $request){
        $this->validate($request, [
            'name' => 'required|unique:broker_group|max:255'
        ]);
        $result = BrokerGroup::create([
            'name'=>$request['name']
        ]);
        if(!$result){
            Toastr::error('新组添加失败!');
            return redirect(route("admin.statistics.groups.create"));
        }
        Toastr::success('新组添加成功!');
         return redirect(route("admin.statistics.groups"));
        
    }

    public function edit($id){
        $group = BrokerGroup::find($id);
        //dd($reply);
        return view("admin.statistics.group.edit",compact('group'));
    }

    public function update(Request $request, $id){

        $this->validate($request, [
            'name' => 'required|max:255'
        ]);

        $data = [
            'name'=>$request['name']
        ];

        $isAble = BrokerGroup::where('id', '<>', $id)->where('name', $data['name'])->count();
        if($isAble) {
           $result= [
                'status' => false,
                'msg' => '名称已被使用'
            ];
            Toastr::error($result['msg']);
        }else{
            $res = BrokerGroup::where('id','=',$id)->update($data);
            if(!$res) {
                $result= [
                    'status' => false,
                    'msg' => '更新失败'
                ];
                Toastr::error($result['msg']);
            }else{
                Toastr::success('更新成功');
            }
            
        }
        return redirect(route('admin.statistics.groups'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $flight = BrokerGroup::find($id);
        //查询是否还有组员
        $agent = BrokerGroupUser::first();
        if(!$agent){
            $result = $flight->delete();
        }
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }


    public function agents(Request $request,$id){
        $group = BrokerGroup::find($id);
        $where=[];
        $whereHas=[];
        $data=['status'=>-1,'name'=>'','type'=>'','mobile'=>'','from'=>'','to'=>''];

        if(!empty($request->all())){
            $datas = $request->all();
            foreach($datas as $k=>$v){
                if(($k=='name' || $k=='mobile') && $v!=''){
                    $whereHas[] = ["$k",'like','%'.$v.'%'];
                }
                if($k=='from' && $v!=''){
                    $where[] = ['created_at','>',$v];
                }
                if($k=='to' && $v!=''){
                    $where[] = ["created_at",'<',$v];
                }
                if($k=='status' && $v!='' && $v!=-1){
                    $where[] = ["$k",'=',$v];
                }
                $data[$k] =$v;
                
            }
        }

        $records = BrokerGroupUser::where('broker_group_id','=',$id)->get();

        foreach($records as $key=>$r){
            //$users = $r->user;
            //$ids = $users->children()->pluck('id')->all();
            $users = User::where('parent_id','=',$r->user_id)->where($where)->get();
            $records[$key]['user_count'] = $users->count();
            $records[$key]['total_user_balance'] = $users->sum('balance');
            //$ids = $users->pluck('id')->all();

             $ids = $r->user->children()->pluck('id')->all();

            //var_dump($ids);
            $options = Option::get();
            $orders_count = 0;
            $total_margin = 0;
            $total_cost = 0;
            $total_earn = 0;
            $total_loss = 0;
            $total_profit = 0;

            foreach($options as $k=>$option){
                    //总单数
                    $count = Order::where($where)->whereIn('user_id',$ids)->where('option_id','=',$option->id)->count();
                    //保证金总额
                    $margin = Order::where($where)->whereIn('user_id',$ids)->where('option_id','=',$option->id)->sum('stop_loss_margin_rmb');
                    //综合费用
                    $cost = Order::where($where)->whereIn('user_id',$ids)->where('option_id','=',$option->id)->sum('transaction_cost_rmb');
                    //用户盈利
                    $earn = Order::where($where)->whereIn('user_id',$ids)->where('option_id','=',$option->id)->where('profit','>',0)->sum('profit');
                    //用户亏损
                    $loss =  Order::where($where)->whereIn('user_id',$ids)->where('option_id','=',$option->id)->where('profit','<',0)->sum('profit');
                    
                    $options[$k]['orders_count'] = $count;
                    $options[$k]['total_margin'] = $margin;
                    $options[$k]['total_cost'] = $cost;
                    $options[$k]['total_earn'] = $earn;
                    $options[$k]['total_loss'] = $loss;
                    $options[$k]['total_profit'] = (-$loss)-$earn;
                    $orders_count += $count;
                    $total_margin += $margin;
                    $total_cost += $cost;
                    $total_profit += $options[$k]['total_profit'];
            }

            $records[$key]['orders_count'] = $orders_count;
            $records[$key]['total_margin'] = $total_margin;
            $records[$key]['total_cost'] = $total_cost;
            $records[$key]['total_profit'] = $total_profit;

            $total_rechages = Recharge::where($where)->where('status','=',1)->whereIn('user_id',$ids)
                            ->sum('money');
            $total_withdrawals = Withdrawals::where($where)
                            ->whereIn('user_id',$ids)->sum('money');
            $total_withdrawals_fee = Withdrawals::where($where)
                            ->whereIn('user_id',$ids)->sum('fee');

            $records[$key]['total_rechages'] = $total_rechages;
            $records[$key]['total_withdrawals'] = $total_withdrawals+$total_withdrawals_fee;
            
            

        }
        return view('admin.statistics.group.agents',compact('group','records','id','data'));
    }

    public function addAgents(Request $request){

        $validator = Validator::make($request->all(), [
            'mobile' => 'required|zh_mobile|max:255',
            'id' => 'required|numeric'
        ]);

        $mobile = $request->mobile;
        $id = $request->id;

        $validator->after(function($validator) use ($mobile,$id){
            if(!$mobile){
                return;
            }
            $user = User::where('mobile','=',$mobile)->first();
            if (!$user) {
                $validator->errors()->add('mobile', '经纪人不存在!');
                return;
            }
            $broker_group = BrokerGroup::find($id);
            if (!$broker_group) {
                $validator->errors()->add('id', '数据错误!');
                return;
            }

            $record = BrokerGroupUser::where('broker_group_id','=',$id)->where('user_id','=',$user->id)->first();
            if ($record) {
                $validator->errors()->add('mobile', '经纪人已在组内!');
                return;
            }

           if ($user && $broker_group && !$record) {
                $result = BrokerGroupUser::create([
                    'broker_group_id'=>$id,
                    'user_id'=>$user->id
                ]);
                if(!$result){
                    $validator->errors()->add('mobile', '添加失败!');
                }
            }

        });

        if ($validator->fails()) {
           //$errors = $validator->errors()->all();
            //Toastr::error(1111);
            return redirect(route('admin.statistics.groups.agents',['id'=>$id]))->withErrors($validator)
                        ->withInput();
        }

       
        
        return redirect(route('admin.statistics.groups.agents',['id'=>$id]));
        //$records = BrokerGroupUser::where('broker_group_id','=',$id)->get();
        //return view('admin.statistics.group.agents',compact('records','id'));
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function agentsDestroy($id)
    {
        $r = BrokerGroupUser::find($id);
        $result = null;
        if($r){
            $result = $r->delete();
        }
        return response()->json($result ? ['status' => 1] : ['status' => 0]);
    }

    public function agentsUsers(Request $request,$id)
    {
        $r = BrokerGroupUser::find($id);

        $ids = $r->user->children()->pluck('id')->all();
        
        $where = [];
        $whereHas = [];
        if($request->has('mobile') && !empty($request['mobile'])){
            $where[] = ['mobile','like','%'.$request['mobile'].'%'];
        }
        if($request->has('name') && !empty($request['name'])){
            $where[] = ['name','like','%'.$request['name'].'%'];
        }
        if($request->has('roleid') && !empty($request['roleid'])){
            $whereHas[] = ['role_id','=',$request['roleid']];

            $users = User::where($where)
                ->whereIn('id',$ids)
                ->whereHas('roles',function($query) use($whereHas){
                            $query->where($whereHas);
                })->orderBy('balance','desc')->get();
                //})->orderBy('balance','desc')->paginate(10);
        }else{
            $users = User::where($where)
                ->whereIn('id',$ids)
                ->orderBy('balance','desc')->get();
        }
        
        return view('admin.statistics.group.agents.users', compact('r','users'));
    }

    public function agentsOrders(Request $request,$id)
    {
        $r = BrokerGroupUser::find($id);

        $ids = $r->user->children()->pluck('id')->all();
        
        $where=[];
        $whereHas=[];
        $data=['name'=>'','option_id'=>0,'mobile'=>'','from'=>'','to'=>''];
        if(!empty($request->all())){
            //if($request->name){
            //dd($request->all());
            //dd(1);
            $datas = $request->all();
            //dd($datas);
            foreach($datas as $k=>$v){
                if(($k=='name' || $k=='mobile') && $v!=''){
                    $whereHas[] = ["$k",'like','%'.$v.'%'];
                }
                if($k=='from' && $v!=''){
                    $where[] = ['close_time','>',strtotime($v)];
                }
                if($k=='to' && $v!=''){
                    $where[] = ["close_time",'<',strtotime($v)];
                }
                if($k=='option_id' && $v!=0){
                    $where[] = ["$k",'=',$v];
                }
                $data[$k] =$v;
                
            }
            //dd($where);
            //$users = User::where($where)->paginate(20);
        }
  
        //var_dump($data);
        $options = Option::get();
        //dd(3);
        $orders = Order::orderBy('id','desc')->whereHas('user',function($query) use($whereHas){
            $query->where($whereHas);
        })->where($where)->whereIn('user_id',$ids)->paginate(20);
        //dd($orders);
        return view('admin.statistics.group.agents.orders',compact('r','orders','data','options'));
        //return view('admin.statistics.group.agents.users', compact('r','users'));
    }


}